package fiuba.descuentos;

import java.util.ArrayList;
import java.util.Vector;

import org.json.JSONException;
import org.json.JSONObject;

import Adapters.CategoryAdapter;
import Entities.Category;
import Service.IService;
import Service.RestServiceFactory;
import Service.WellKnownMethods;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Categories extends ActivityBase {
	private ArrayList<Category> categories;
	private GridView listview_categories;
		
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.categories);
        init();
    }		

	private void init() {
		getItems();
	}
	
	private void createMocks(){
		this.categories = Category.createMocks();
		bindItems();
	}

	private void getItems() {
		Vector props = new Vector();
		callService(WellKnownMethods.GetCategories, props);
		//createMocks();		
	}

	
	private void bindItems(){		
		listview_categories = (GridView) findViewById(R.id.list_categories);
		checkScreenOrientation();
		CategoryAdapter listAdapter = new CategoryAdapter(R.layout.category_column, categories);
		listview_categories.setAdapter(listAdapter);
		listview_categories.setVisibility(View.VISIBLE);	
		listview_categories.setOnItemClickListener(new OnItemClickListener() {
	        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
	        	Intent intent = new Intent(parent.getContext(), CategoryBenefit.class);
	        	intent.putExtra("category", categories.get(position));
	        	startActivity(intent);
	        }
	    });
			
	}
	
	private void checkScreenOrientation() {
		
		if(this.orientation ==  Configuration.ORIENTATION_PORTRAIT){
			listview_categories.setNumColumns(2);			
		}else{
			listview_categories.setNumColumns(4);
		}				
	}
		
	@Override
	public void onServiceCompleted(JSONObject obj, String method) {
		if (WellKnownMethods.GetCategories.compareTo(method) == 0){
			onGetCategoriesCompleted(obj);
		}
	}

	private void onGetCategoriesCompleted(JSONObject obj) {
		boolean resultSuccess;
		hideLoading();
		try {
			resultSuccess = obj.getBoolean("success");
			if (resultSuccess) {
				this.categories = Category.getFromJSON(obj);
				bindItems();
			}else{
				showErrorMessage(obj.getString("message"));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}				
	}	
}